<template>
	<div class="homework-page">
		<van-tabs v-model:active="tabIndex" color="#0CB76C" background="#f5f5f5" line-width="28"
			title-active-color="#0CB76C" title-inactive-color="#333333" @click-tab="handleTabChange">
			<van-tab v-for="item in tabData" :key="item.id" :title="item.name" title-style="font-size: 18px;">

			</van-tab>
		</van-tabs>
		<Mescroll v-bind="mescrollConfig" :style="{
			height: 'calc(100vh - 44px)',
			position: 'fixed',
			top: '54px',
			bottom: 0,
		}" @init="mescrollInited">
			<div class="work" v-for="work in homeworkList" :key="work.id">
				<!-- 课后作业 -->
				<template v-if="work.operation === 1">
					<div class="item-title">
						<img src="@/assets/images/time.png" width="14" height="14" />
						<div class="item-progress">{{ getWorkStatus(work.deadlinetime) }}</div>

						<van-popover class="pop-icon-more" placement="bottom-end">
							<div class="pop-list">
								<div class="pop-item">
									<div class="item-name">作业名称</div>
									<div class="item-value">{{ work.name }}</div>
								</div>
								<div class="pop-item">
									<div class="item-name">开始时间</div>
									<div class="item-value">{{ dateFormat(work.startTime) }}</div>
								</div>
								<div class="pop-item">
									<div class="item-name">截止时间</div>
									<div class="item-value">{{ dateFormat(work.deadlinetime) }}</div>
								</div>
								<div class="pop-item">
									<div class="item-name">作业选项</div>
									<div class="item-value">
										{{ homeworkOptionsText(work.checkinfo, work.repair) }}
									</div>
								</div>
								<div class="pop-item">
									<div class="item-name">作业留言</div>
									<div class="item-value">{{ work.message }}</div>
								</div>
							</div>
							<template #reference>
								<img class="icon-more" src="@/assets/images/wrongBook/icon-more.png" width="18"
									height="4" />
							</template>
						</van-popover>
					</div>

					<van-divider :style="{ borderColor: '#E5E5E5', margin: '15px 0' }" />
					<div class="item" v-for="(course, index) in work.rid_arr" :key="course.id"
						@click="goDetailPage(work, course)">
						<div class="test-detail">
							<img src="@/assets/images/listen.png" width="20" height="20" />
							<div class="title-name">{{ course.resourceName }}</div>
							<div class="test-unfinished">
								{{ course.student_exam_num === 1 ? "未" : "已" }}完成
							</div>
						</div>
						<div class="test-time">
							<div class="test-require" v-if="course.teacher_talk_num || course.student_talk_num">
								老师要求读<b class="highlight-red">{{ course.teacher_talk_num }}次</b>，已读<b
									class="highlight-green">{{
										course.student_talk_num }}次</b>
							</div>
							<div class="test-progress">
								{{ course.homework_percentage }}同学已完成
							</div>
						</div>
						<van-divider v-if="index < work.rid_arr.length - 1"
							:style="{ borderColor: '#E5E5E5', margin: '15px 0' }" />
					</div>
				</template>

				<!-- 机房考试 -->
				<div class="item" v-else-if="work.operation === 2" @click="goDetailPage(work, course)">
					<div class="test-status">
						<div class="test-icon tag-yellow">
							{{ getWorkStatus(work.deadlinetime).slice(0, 3) }}
						</div>
						<div class="time-end">{{ dateFormat(work.deadlinetime) }}截止</div>
						<img src="@/assets/images/wrongBook/icon-arrow-right-gray.png" width="7" height="12" />
					</div>
					<van-divider :style="{ borderColor: '#E5E5E5' }" />
					<div class="test-detail">
						<img src="@/assets/images/listen.png" width="20" height="20" />

						<div class="title-box">
							<div class="title-name">{{ work.rid_arr[0].resourceName }}</div>
							<div class="title-tag">考</div>
						</div>

						<div class="title-status">
							<div class="test-unfinished" v-if="work.rid_arr[0].student_exam_num === 1">
								未完成
							</div>
							<div class="test-finished" v-else>
								{{ work.rid_arr[0].student_exam_fraction }}
							</div>
						</div>
					</div>
					<div class="test-time" v-if="work.rid_arr[0].student_exam_num === 2">
						{{ work.rid_arr[0].exam_fraction }}分
					</div>
				</div>
			</div>
		</Mescroll>
		<van-popup v-model:show="showPopup" position="bottom">
			<div class="popupBox">
				<div class="moreBox">
					<div class="block"></div>
					<div>更多</div>
				</div>
				<div class="againBox" @click="gotoWord">
					<img src="@/assets/images/icon-white-horn.png" />
					<div>再做一次</div>
				</div>
				<div class="detailBox" @click="lookWorkDetail">
					<img src="@/assets/images/icon-check-detail.png" />
					<div>查看详情</div>
				</div>
				<div class="close" @click="showPopup = false">关闭</div>
			</div>
		</van-popup>
		<NoResult v-if="homeworkList.length === 0 && !loading.tab" />
		<van-loading class="tab-loading" size="24px" v-if="loading.tab" vertical>加载中...</van-loading>
		<AppLoading v-if="loading.page" />
	</div>
</template>

<script setup>
	import {
		onMounted,
		onUnmounted,
		reactive,
		toRefs,
		nextTick,
	} from "vue";
	import {
		useRoute,
		useRouter,
	} from "vue-router";
	import {
		showToast
	} from "vant";
	import Mescroll from "mescroll.js/mescroll.vue";

	import {
		request
	} from "@/api/request.js";
	import AppLoading from "@/components/AppLoading.vue";
	import NoResult from "./noResult.vue";
	import {
		dateFormat,
		getWorkStatus
	} from "@/utils/dateFormat";

	const route = useRoute();
	const router = useRouter();
	const state = reactive({
		loading: {
			page: false,
			tab: false,
		},
		showPopup: false,
		homeworkList: [],
		homeworkDetail: {},
		tabIndex: 0,
		mescrollInstance: null,
		mescrollConfig: {
			down: {
				use: true,
			},
			up: {
				auto: true,
				isBounce: false,
				noMoreSize: 1,
				htmlNodata: '<p class="upwarp-nodata">-- 无更多数据 --</p>',
				callback: (page) => {
					fetchHomeworkData(page);
				},
			},
		},
	});

	const tabData = [{
			id: 1,
			name: "课后作业",
		},
		{
			id: 2,
			name: "机房考试",
		},
		// {
		//   id: 3,
		//   name: "课堂教学",
		// },
		// {
		//   id: 4,
		//   name: "打卡",
		// },
	];

	const homeworkOptionsText = (checkinfo, repair) => {
		const options = {
			1: {
				1: "详情可查看 可补交",
				0: "截止后不可补交",
			},
			0: {
				1: "截止后可补交",
				0: "截止后不可补交",
			},
		};

		return options[+checkinfo][repair];
	};

	onMounted(() => {
		state.loading.page = true;
		// handleTabChange({name:0})
		state.tabIndex = +route.query.operation - 1 || state.tabIndex;
	});
	onUnmounted(() => {
		state.mescrollInstance.setBounce(true)
		state.mescrollInstance.destroy();
	})

	const mescrollInited = (mescroll) => {
		state.mescrollInstance = mescroll;
	};

	const handleTabChange = async ({
		name
	}) => {
		state.tabIndex = name;
		state.loading.tab = true;
		state.homeworkList = [];
		fetchHomeworkData({
			num: 1,
			page: 10
		});
		state.mescrollInstance.scrollTo(0, 0);
	};

	const fetchHomeworkData = ({
		num,
		size = 10
	}) => {
		request({
				url: "/api/homework/getStudentHomeworkList",
				method: "post",
			}, {
				data: {
					operation: state.tabIndex + 1,
					page: num,
					pageSize: size,
				},
			})
			.then((res) => {
				const {
					code,
					data
				} = res;
				if (+code === 1 && data) {
					const isNestPage = data.length < size;
					isNestPage && state.mescrollInstance.endDownScroll();
					if (num === 1) {
						state.homeworkList = data;
					} else {
						state.homeworkList = state.homeworkList.concat(data);
					}
					state.homeworkList = state.homeworkList.map((item) => ({
						...item,
						showMoreInfo: false,
					}));
					nextTick(() => {
						state.mescrollInstance.endSuccess(state.homeworkList.length, !isNestPage);
					});
				} else {
					throw res;
				}
			})
			.catch((e) => {
				showToast(e.msg || (e.body && e.body.msg));
			})
			.finally(() => {
				state.loading.tab = false;
				state.loading.page = false;
			});
	};

	const gotoWord = () => {
		// ptype书籍类型：1听说 2听力 3跟读 4笔试 5音标 6典范 7新概念 8黑布林 9教材同步

		let pathMap = {
			'a7527f97-14e6-44ef-bf73-3039033f128e': '/homework/followWordH5',
			'992a5055-e9d0-453f-ab40-666b4d7030bb': '/homework/followTextH5',
		}
		let query = {};
		let nameMap = {
			'a7527f97-14e6-44ef-bf73-3039033f128e': '单词',
			'992a5055-e9d0-453f-ab40-666b4d7030bb': '课文',
		}
		let path = pathMap[state.homeworkDetail.resourceType];
		switch (state.homeworkDetail.ptype) {
			case 1:
				const userAgent = navigator.userAgent.toLowerCase();
				if (/android/.test(userAgent)) {
					window.android.gotoHearSayPage(state.homeworkDetail.versionId, state.homeworkDetail.resourceName,
						state
						.homeworkDetail.id);
				} else if (/iphone|ipad|ipod/.test(userAgent)) {
					const message = {
						versionId: state.homeworkDetail.versionId,
						resourceName: state.homeworkDetail.resourceName,
						mission_id: state.homeworkDetail.id,
					};
					window.webkit.messageHandlers.gotoHearSayPage.postMessage(message);
				}

				break;
			case 2:
				path = '/listening/book-unit';
				query = {
					versionId: state.homeworkDetail.versionId,
					title: state.homeworkDetail.resourceName,
					mission_id: state.homeworkDetail.id,
				}
				break;
			case 3:
				query = {
					versionId: state.homeworkDetail.versionId,
					resourceFile: state.homeworkDetail.resourceUrl,
					title: state.homeworkDetail.resourceName,
					mode: "Follow",
					module: 'repeat',
					mission_id: state.homeworkDetail.id,
					moduleName: nameMap[state.homeworkDetail.resourceType],
				}
				break;
			case 4:
				path = '/writtenTest/detailsUnit';
				query = {
					versionId: state.homeworkDetail.versionId,
					productId: state.homeworkDetail.pid,
					mission_id: state.homeworkDetail.id,
					title: state.homeworkDetail.resourceName,
				}
				break;
			case 5:
				//待定
				pathMap = {
					'a7527f97-14e6-44ef-bf73-3039033f128e': '/phoneticSymbol/followRead',
					'992a5055-e9d0-453f-ab40-666b4d7030bb': '/phoneticSymbol/reatic',
					'c458a8d4-e3ca-403c-b6b2-ae166e955590': '/phoneticSymbol/reat',
					'05a3bf23-b65b-4d7f-956c-5db2b76b9c11': '/phoneticSymbol/points',
				}
				query = {
					id: state.homeworkDetail.versionId,
					mission_id: state.homeworkDetail.id,
					apiKey: 'soundmark',
					type: 'follow',
				}
				break;
			case 6:
				query = {
					versionId: state.homeworkDetail.versionId,
					resourceFile: state.homeworkDetail.resourceUrl,
					title: state.homeworkDetail.resourceName,
					mode: "Follow",
					module: 'model',
					mission_id: state.homeworkDetail.id,
					moduleName: nameMap[state.homeworkDetail.resourceType],
				}
				break;
			case 7:
				query = {
					versionId: state.homeworkDetail.versionId,
					resourceFile: state.homeworkDetail.resourceUrl,
					title: state.homeworkDetail.resourceName,
					mode: "Follow",
					module: 'newconcept',
					mission_id: state.homeworkDetail.id,
					moduleName: nameMap[state.homeworkDetail.resourceType],
				}
				break;
			case 8:
				query = {
					versionId: state.homeworkDetail.versionId,
					resourceFile: state.homeworkDetail.resourceUrl,
					title: state.homeworkDetail.resourceName,
					mode: "Follow",
					module: 'black_plum',
					mission_id: state.homeworkDetail.id,
					moduleName: nameMap[state.homeworkDetail.resourceType],
				}
				break;
			case 9:
				query = {
					versionId: state.homeworkDetail.versionId,
					resourceFile: state.homeworkDetail.resourceUrl,
					title: state.homeworkDetail.resourceName,
					mode: "Follow",
					module: 'textbook_synchronization',
					mission_id: state.homeworkDetail.id,
					moduleName: nameMap[state.homeworkDetail.resourceType],
				}
				break;
			default:
				break;
		}
		router.push({
			path,
			query,
		});
	}

	const lookWorkDetail = () => {
		// ptype书籍类型：1听说 2听力 3跟读 4笔试 5音标 6典范 7新概念 8黑布林 9教材同步
		let url = null;
		if (state.homeworkDetail.ptype == 1) {
			url = "homework-speak"
		} else if (state.homeworkDetail.ptype == 2) {
			url = "homework-linstening"
		} else if (state.homeworkDetail.ptype == 3 || state.homeworkDetail.ptype == 6 || state.homeworkDetail.ptype ==
			7 || state.homeworkDetail.ptype == 8 || state.homeworkDetail.ptype == 9) {
			url = "homework-followReading"
		} else {
			console.log("该类型题目未解析")
		}
		// 已完成
		router.push({
			path: url,
			query: {
				id: state.homeworkDetail.id, //试卷ID
				versionId: state.homeworkDetail.versionId, //资源练习id
				mission_type: state.homeworkDetail.type, //答题模式：0=课后作业 1=练习 2=测试 3=考试
			},
		});
	}

	const goDetailPage = (work, item) => {
		state.homeworkDetail = {
			id: work.id,
			type: work.type,
			ptype: work.ptype,
			...item,
			resourceUrl: item.resourceUrl.includes('json') ? item.resourceUrl : item.resourceUrl +
				'.json', // 部分数据链接不包含‘.json’
		}
		if (item.student_exam_num == 2) {
			state.showPopup = true
		} else {
			gotoWord()
		}
	};

	const {
		loading,
		showPopup,
		homeworkList,
		homeworkDetail,
		tabIndex,
		mescrollConfig
	} = toRefs(state);
</script>

<style scoped lang="scss">
	.popupBox {
		font-size: 16px;
		padding: 20px 0;

		.againBox,
		.detailBox {
			display: flex;
			align-items: center;
			padding: 20px 20px;
			border-bottom: 1px solid #E5E5E5;
		}

		img {
			width: 20px;
			height: 20px;
			margin-right: 15px;
		}

		.moreBox {
			display: flex;
			align-items: center;
			padding: 10px 20px;
			border-bottom: 1px solid #E5E5E5;

			.block {
				width: 4px;
				height: 14px;
				margin-right: 14px;
				background: #0CB76C;
				;
			}
		}

		.close {
			margin: 30px 20px 0;
			height: 45px;
			background: linear-gradient(270deg, #29F19C 0%, #02A1F9 100%);
			border-radius: 23px;
			color: #ffffff;
			line-height: 45px;
			text-align: center;
		}
	}

	.homework-page {
		font-family: PingFangSC, PingFang SC;
		min-height: 100%;
		background: #f5f5f5;
	}

	.tab-loading {
		margin-top: 250px;
	}

	.work {
		background: #ffffff;
		border-radius: 15px;
		padding: 15px 10px;
		box-sizing: border-box;
		margin: 0 10px 10px;
	}

	.item-title {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.item-progress {
		font-weight: 500;
		font-size: 12px;
		color: #0cb76c;
		line-height: 20px;
		text-align: left;
		font-style: normal;
		flex: 1;
		margin-left: 5px;
	}

	.test-require {
		margin-left: 25px;
	}

	.test-progress {
		flex: 1;
	}

	.pop-icon-more {
		transform: translate(10px, 10px);
	}

	.icon-more {
		display: flex;
	}

	.pop-list {
		width: 257px;
		padding: 15px 15px 5px;
		box-sizing: border-box;
	}

	.pop-item {
		font-weight: 500;
		font-size: 12px;
		margin-bottom: 10px;
		display: flex;
	}

	.item-name {
		color: #8e8e8e;
	}

	.item-value {
		color: #333333;
		margin-left: 10px;
		max-width: 168px;
	}

	.highlight-red {
		color: #fa192c;
	}

	.highlight-green {
		font-weight: normal;
		color: #0cb76c;
	}

	.test-status {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 10px;
		box-sizing: border-box;
	}

	.test-icon {
		width: 56px;
		height: 20px;
		line-height: 20px;
		text-align: center;
	}

	.tag-blue {
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 12px;
		color: #0287fd;
		font-style: normal;
		background: url("../../assets/images/tag-blue.png") no-repeat center / 100% 100%;
		display: inline-block;
	}

	.tag-yellow {
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 12px;
		color: #ff9917;
		font-style: normal;
		background: url("../../assets/images/tag-yellow.png") no-repeat center / 100% 100%;
		display: inline-block;
	}

	.time-end {
		font-weight: 500;
		font-size: 12px;
		color: #8e8e8e;
		line-height: 20px;
		text-align: left;
		font-style: normal;
		flex: 1;
		margin-left: 5px;
	}

	.test-detail {
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
		font-weight: 500;
		font-size: 12px;
		line-height: 20px;
		text-align: right;
		font-style: normal;
		margin-bottom: 5px;
	}

	.title-box {
		display: flex;
	}

	.title-name {
		font-weight: 500;
		font-size: 16px;
		color: #333333;
		line-height: 20px;
		text-align: left;
		font-style: normal;
		margin-left: 5px;
		margin-right: 5px;
		flex: 1;
	}

	.title-tag {
		width: 20px;
		height: 20px;
		background: #0cb76c;
		border-radius: 6px;
		font-weight: 500;
		font-size: 12px;
		color: #ffffff;
		line-height: 20px;
		text-align: center;
		font-style: normal;
	}

	.title-status {
		flex: 1;
	}

	.test-unfinished {
		color: #8e8e8e;
	}

	.test-finished {
		color: #0cb76c;
	}

	.test-time {
		height: 20px;
		font-weight: 500;
		font-size: 12px;
		color: #8e8e8e;
		text-align: right;
		font-style: normal;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		flex-direction: row;
		justify-content: flex-end;
	}
</style>